package org.apache.ocean.main.search;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.ocean.main.Snapshot;
import org.apache.ocean.main.search.cache.RangeDocSetCacheKey;
import org.apache.ocean.main.util.Range;
import org.apache.ocean.main.util.Timeout;

public class ConstantScoreRangeQuery extends Query {
	private final String fieldName;
	private final Range range;
	private final Snapshot snapshot;
	private final Timeout timeout;

	public ConstantScoreRangeQuery(String fieldName, Range range, Snapshot snapshot, Timeout timeout) {
		this.snapshot = snapshot;
		this.timeout = timeout;
		this.fieldName = fieldName.intern(); 
		this.range = range;
	}
  
	public Query rewrite(IndexReader reader) throws IOException {
		RangeDocSetCacheKey rangeCacheKey = new RangeDocSetCacheKey(fieldName, range);
		Query q = new ConstantScoreQuery(rangeCacheKey, snapshot, timeout);
		q.setBoost(getBoost());
		return q;
	}
	
	/** Returns the field name for this query */
	public String getField() {
		return fieldName;
	}
  
	public Range getRange() {
		return range;
	}
	
	public String toString(String field) {
		StringBuilder buffer = new StringBuilder();
		if (!getField().equals(field)) {
			buffer.append(getField());
			buffer.append(":");
		}
		buffer.append(range.toString());
		if (getBoost() != 1.0f) {
			buffer.append("^");
			buffer.append(Float.toString(getBoost()));
		}
		return buffer.toString();
	}

	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (!(o instanceof ConstantScoreRangeQuery))
			return false;
		ConstantScoreRangeQuery other = (ConstantScoreRangeQuery) o;

		return this.fieldName == other.fieldName
				&& range.equals(other.getRange()) && this.getBoost() == other.getBoost();
	}
}
